package com.sqbang.dbcompare;

import com.sqbang.dbcompare.config.PathConfig;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * 启动类
 * @author suqiongbang
 * @date 2020/12/28 10:27
 */
@SpringBootApplication
public class DatabaseCompareApplication {

    @Autowired
    PathConfig pathConfig;

    public static void main(String[] args) {
        SpringApplication.run(DatabaseCompareApplication.class, args);
    }

    @Bean
    public void loadTemplate() {
        // 参考：https://www.cnblogs.com/qingshanli/p/11730400.html
        ApplicationHome applicationHome = new ApplicationHome(DatabaseCompareApplication.class);
        // 项目打包成jar包所在的根路径
        String rootPath = applicationHome.getSource().getParentFile().toString() + File.separator + pathConfig.getTemplateDiskDir();
        File configDir = new File(rootPath);
        if (!configDir.exists() || !configDir.isDirectory()) {
            configDir.mkdirs();
        }
        String configFilePath = rootPath + File.separator + pathConfig.getTemplateFileName();
        File configFile = new File(configFilePath);
        if (!configFile.exists()) {
            try {
                //获取类路径下的指定文件流
                InputStream in = this.getClass().getClassLoader().getResourceAsStream(pathConfig.getTemplateJarPath());
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(in, String.format("%s文件找不到", pathConfig.getTemplateFileName())), configFile);
            } catch (IOException e) {
                throw new IllegalArgumentException(String.format("加载%s文件到磁盘失败", pathConfig.getTemplateFileName()));
            }
        }
    }
}
